package com.nakanomay.redislock.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author nakano_may丶
 * @version 1.0
 * @create 2023-05-08 22:33
 * @description：
 */
@Service
@Slf4j
public class InventoryService
{
    @Resource private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}") private String port;

    private Lock lock = new ReentrantLock();

    public String sale()
    {
        String retMessage = "";

        lock.lock();

        try
        {
            // 1 查询库存信息
            String result = stringRedisTemplate.opsForValue().get("inventory001");
            // 2 判断库存是否足够
            Integer inventoryNumber = result == null? 0 : Integer.parseInt(result);
            // 3 减库存，每次减少一个
            if (inventoryNumber > 0)
            {
                stringRedisTemplate.opsForValue().set("inventory001", String.valueOf(--inventoryNumber));
                retMessage = "成功卖出一个商品，库存剩余： " + inventoryNumber;
                System.out.println(retMessage + "\t 服务端口号Port: " + port);
            } else {
                retMessage = "没有可以卖出任何商品，库存： " + --inventoryNumber + "\tPort: " + port;
                System.out.println(retMessage + "\t 服务端端口号Port: " + port);
            }
        }
        finally
        {
            lock.unlock();
        }
        return retMessage + "\t" +"服务端口号Port: " + port;
    }
}
